package com.dy.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.common.R;
import com.dy.entity.ShoppingCart;
import com.dy.mapper.ShoppingCartMapper;
import com.dy.service.ShoppingCartService;
import com.dy.utils.CurrentHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    /**
     * @Author dy
     * @Description:  用户购物车 添加商品
     */
    @Transactional
    public R<ShoppingCart> addShoppingCart(ShoppingCart shoppingCart) {
        //添加的购物 附上当前用户ID
        shoppingCart.setUserId(CurrentHolder.getCurrent());
        //添加上  默认数量 “1”
        shoppingCart.setNumber(1);
        //添加当前时间
        shoppingCart.setCreateTime(LocalDateTime.now());
        //避免口味为null
        if(StringUtils.isBlank(shoppingCart.getDishFlavor())){
            shoppingCart.setDishFlavor("");
        }
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper();
        //判断当前添加的是  菜品/套餐
        if(shoppingCart.getDishId() != null){
            //添加的 是菜品
            // 添加 过滤条件 用户ID/菜品ID/口味
            queryWrapper.eq(ShoppingCart::getUserId,shoppingCart.getUserId());
            queryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
            queryWrapper.eq(ShoppingCart::getDishFlavor,shoppingCart.getDishFlavor());
            //加上 last 执行的sql 最后会 加上 limit 1
            queryWrapper.last("limit 1");
        }else{
            //添加套餐
            //添加 当前用户条件 套餐ID
            queryWrapper.eq(ShoppingCart::getUserId,shoppingCart.getUserId());
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
            //加上 last 执行的sql 最后会 加上 limit 1
            queryWrapper.last("limit 1");
        }
        //查找Mysql
        ShoppingCart one = this.getOne(queryWrapper);

        if(one != null){
            //数据 已被加入购物车  数量 + 1
            one.setNumber(one.getNumber() + 1);
            this.updateById(one);
        }else{
            //数据还未加入购物车 新增数据
            this.save(shoppingCart);
            one = shoppingCart;
        }
        //返回新增的数据信息
        return R.success(one);
    }
}
